package service

import (
	"common/global"
	userApi "common/proto/api"
	"context"
	"core/dao"
	"core/models/entity"
	"core/models/request"
	"go.uber.org/zap"
	"time"
)

type UserServer struct {
	userApi.UnimplementedUserServiceServer
	AccountDao *dao.AccountDao
	RedisDao   *dao.RedisDao
}

func NewUserServer() *UserServer {
	return &UserServer{
		AccountDao: dao.NewAccountDao(global.Manager),
		RedisDao:   dao.NewRedisDao(global.Manager),
	}
}

/*
*
注册服务
*/
func (c *UserServer) Register(ctx context.Context, req *userApi.RegisterParams) (*userApi.RegisterResponse, error) {
	//判断是否是微信注册
	if req.LoginPlatform == request.WeiXin {
		account, err := c.WxRegister(ctx, req)
		if err != nil {
			return nil, err
		}
		return &userApi.RegisterResponse{Uid: account.Uid}, nil
	}
	return nil, nil
}

/*
*
微信注册
*/
func (c *UserServer) WxRegister(ctx context.Context, request *userApi.RegisterParams) (*entity.Account, error) {
	//1 查询微信是否被注册了
	accountEntity := entity.Account{
		Account: request.Account,
	}
	queryAccountEntity := c.AccountDao.QueryAccountByAccount(ctx, &accountEntity)
	if queryAccountEntity != nil { //查询到注册信息
		return queryAccountEntity, nil
	}
	//2 没有则进行注册
	uid, err := c.RedisDao.NextAccountId()
	if err != nil {
		zap.S().Errorf("generate uid err:%v", err)
		return nil, err
	}
	registerAccount := entity.Account{
		Uid:        uid,
		Account:    request.Account,
		Password:   "888888",
		CreateTime: time.Now(),
	}
	err = c.AccountDao.SaveAccount(ctx, &registerAccount)
	if err != nil {
		zap.S().Errorf("saveAccount err:%v", err)
		return nil, err
	}
	return &registerAccount, nil
}

//手机注册
